import React, { PureComponent } from 'react'

import store from '../store'

export default function connect(mapStateToProps, mapDispatchToProps) {
  return function wrapComponentHOC(WrappedComponent) { 
    return class NewComponent extends PureComponent {
      constructor(props){
        super(props)
        this.state = {
          storeState: mapStateToProps(store.getState())
        }
      }
    
      componentDidMount(){
        // 订阅赋值后界面才会改变
        this.unsubscribe = store.subscribe(() => {
          this.setState({storeState: mapStateToProps(store.getState())})
        })
      }
    
      componentWillUnmount(){
        this.unsubscribe()
      }
    
      render() {
        return <WrappedComponent {...this.props} 
          {...mapStateToProps(store.getState())} {...mapDispatchToProps(store.dispatch)}/>
      }
    }
  }
}